package com.ck.file.controller;

import com.ck.common.BaseTask;
import com.ck.common.constant.AjaxResult;
import com.ck.common.utils.date.DateUtils;
import com.ck.common.utils.txt.StringUtils;
import com.ck.common.utils.file.FileUtils;
import com.ck.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author ck
 * @date 2023/8/24 14:48
 */
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController extends BaseTask {

    @Autowired
    FileService fileService;

    @Value("${file.downLoad}")
    private String downLoad;


    /**
     * 文件上传 指将本地计算机上的文件传输到Web服务器上
     */
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file, HttpServletRequest request){
        log.info("文件开始上传");
        try {
            long start = taskStart();
            String url = fileService.uploadFile(file,request);
            AjaxResult result = new AjaxResult();
            result.put("Name", FileUtils.getName(url));
            result.put("url",url);
            taskEnd(start);
            log.info("文件上传结束");
            return result;
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 文件下载 是从Web服务器获取文件并保存到本地计算机的过程(在服务器端，设置合适的HTTP响应头，以便浏览器将文件识别为下载文件。
     * 这通常涉及设置"Content-Disposition: attachment"头，并将文件内容写入响应流)
     * @param fileName
     * @param response
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, HttpServletResponse response)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            //新文件名(唯一)
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            //获取服务器上文件保存的路径
            String filePath = downLoad + "/"+ fileName;

            //二进制
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }


    /***
     * 解压指定目录下的文件接口
     * @return
     * @throws Exception
     */
    @PostMapping("/unzip")
    public AjaxResult unzip() throws Exception {
        log.info("=============================当前时间"+ DateUtils.dateTime(new Date()) +"，获取指定文件夹内所有的压缩包==========================================================");
        String result = fileService.extractTarGz();
        return AjaxResult.success(result);
    }


}
